#!/usr/bin/perl -w

BEGIN {
    $ENV{CATALYST_ENGINE} ||= 'HTTP';
    $ENV{CATALYST_SCRIPT_GEN} = 30;
    require Catalyst::Engine::HTTP;
}

use strict;
use warnings;
use Getopt::Long;
use Pod::Usage;
use FindBin;
use lib "$FindBin::Bin/../lib";

my $debug      = 0;
my $droptables = 0;
my $help       = 0;

my @argv = @ARGV;

GetOptions(
    'debug|d'      => \$debug,
    'droptable|dt' => \$droptables,
    'help|?'       => \$help,
);

pod2usage(1) if $help;

if ($debug) {
    $ENV{CATALYST_DEBUG} = 1;
}

sub deploy_dir {
    my $dir = shift;
    my $log = Askgene->log;
    if ( -e $dir ) {
        $log->fatal("${dir} exists and is a plain file") && return
          if -f _;
        $log->fatal("${dir} isn't a directory") && return unless -d _;
        $log->debug("directory exists: ${dir}")
          if Askgene->debug;
    }
    else {
        $dir->mkpath
          or $log->fatal("Couldn't create directory ${dir}: $!") && return;
        $log->debug("Created directory: $dir")
          if Askgene->debug;
    }
}

sub deploy_schema {
    Askgene->model('Database')
      ->schema->deploy( { add_drop_table => $droptables } );
    Askgene->log->debug('Deployed database') if Askgene->debug;
}

# This is require instead of use so that the above environment
# variables can be set at runtime.
require Askgene;

deploy_dir(
    Askgene->model('Queue')->work_dir
      or die "Model::Queue work_dir config isn't set"
);
deploy_schema();

Askgene->log->_flush;

1;

=head1 NAME

askgene_deploy.pl - Askgene deployment script

=head1 SYNOPSIS

askgene_deploy.pl [options]

 Options:
   -dt -droptables    drop tables before creating new ones
   -d -debug          force debug mode
   -? -help           display this help and exits

=head1 DESCRIPTION

Deploy the Askgene application

=head1 AUTHOR

Eden Cardim C<edencardim@gmail.com>

=head1 COPYRIGHT

This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut
